package com.haipumi.filters;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Hashtable;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.reflect.TypeToken;
import com.haipumi.redis.GetShardedJedis;
import com.haipumi.utils.CommonData;
import com.haipumi.utils.GetNowTime;
import com.haipumi.utils.GetRequestIp;
import com.haipumi.utils.GsonUtil;
import com.haipumi.utils.LogUtil;

import redis.clients.jedis.ShardedJedis;

/**
 * 记录首页的浏览次数
 * @author Administrator
 */
public class IndexViewsFilter implements Filter {
//	private Jedis jedis = new Jedis("localhost");//普通的实例化获取
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		ShardedJedis jedis=GetShardedJedis.getShardedJedis();//从池中获取redis
		//获取登陆信息
		HttpServletRequest request=(HttpServletRequest) arg0;
		HttpServletResponse response=(HttpServletResponse) arg1;
		HttpSession session=request.getSession();
		StringBuffer sb=request.getRequestURL();
		//证明是查看详情
		String op=request.getParameter("op");
		if("indexFindTask".equals(op)){
			//首页总浏览次数++
			String today=GetNowTime.getNowTime("yyyy-MM-dd");
			IndexViewsRedis(CommonData.indexViewsRedisKey,today);
			//该IP浏览次数++
			String Ip=GetRequestIp.getRemoteHost(request);
			IndexViewsRedis(CommonData.IPViewsRedisKey,Ip);
			
			LogUtil.log.debug("首页的总浏览次数是"+jedis.get(CommonData.indexViewsRedisKey));
			LogUtil.log.debug(Ip+"对首页浏览次数是"+jedis.get(CommonData.IPViewsRedisKey));
		}
		GetShardedJedis.ReturnShardedJedis(jedis);
		arg2.doFilter(arg0, arg1);
	}

	//存储浏览次数
	private void IndexViewsRedis(String MapKey,String valueKey) {
		ShardedJedis jedis=GetShardedJedis.getShardedJedis();//从池中获取redis
		String jsonString=jedis.get(MapKey);
		Hashtable<String,Integer>  map;//存储对象
		Integer total=1;//浏览总计
		if(jsonString!=null && jsonString!=""){//如果已经有数据
			Type objectType = new TypeToken< Hashtable<String,Integer> >(){}.getType();
			map=(Hashtable<String,Integer> ) GsonUtil.JsonToObject(jsonString, objectType);//将他转为一个map
			if(map.containsKey(valueKey)){//说明已经有值
				total=map.get(valueKey)+1;
			}
		}else{
			map=new Hashtable<String,Integer>();
		}
		map.put(valueKey, total);//更新浏览次数
		String jsonParams=GsonUtil.getJsonString(map);//将map转为json数据
		jedis.set(MapKey, jsonParams);//更新值
		GetShardedJedis.ReturnShardedJedis(jedis);
	}
	
	@Override
	public void init(FilterConfig arg0) {
	}
}
